package patrol.mobile.com.mobilepatrol.manager;

import io.realm.Realm;
import io.realm.RealmResults;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.bean.User;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;

import static patrol.mobile.com.mobilepatrol.PatrolApp.realm;

/**
 * Created by apple on 17/9/27.
 */

public class UserManager {

    public static RealmResults<User> getUsers() {
        return realm.where(User.class).findAll();
    }

    public static boolean isExit2(String user) {
        RealmResults<User> list = PatrolApp.realm.where(User.class).equalTo("username", user).findAll();
        if (list == null || list.size() == 0) {
            return false;
        } else {
            return true;
        }
//        RealmResults<User> users = getUsers();
//        for (int i = 0; i < users.size(); i++) {
//            if (user.equals(users.get(i).username)) {
//                return true;
//            }
//
//        }
//        return false;
    }

    public static User isExit2(String user, String pwd) {
        RealmResults<User> users = getUsers();
        for (int i = 0; i < users.size(); i++) {
            if ((user).equals(users.get(i).username) && (pwd).equals(users.get(i).pw)) {
                return users.get(i);
            }

        }
        return null;
    }

    public static void delUsers() {
        final RealmResults<User> users = getUsers();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                users.deleteAllFromRealm();
            }
        });

    }

    public static User getUser(String id) {
        RealmResults<User> list = realm.where(User.class).equalTo("ryid", id).findAll();
        if (list != null && list.size() > 0) {
            return realm.where(User.class).equalTo("ryid", id).findAll().get(0);
        } else {
            return null;
        }

    }

    public static User getUser() {
        RealmResults<User> list = realm.where(User.class).equalTo("ryid", getUserId()).findAll();
        if (list != null && list.size() > 0) {
            return realm.where(User.class).equalTo("ryid", getUserId()).findAll().get(0);
        } else {
            return null;
        }

    }

    public static String getUserId() {
        return getUser((String) SPUtils.get(Constants.current_id, "")).ryid;
    }

    public static String getOrgNo() {
        return getUser((String) SPUtils.get(Constants.current_id, "")).bmcode;
    }

    public static String getUserName() {
        return getUser((String) SPUtils.get(Constants.current_id, "")).username;
    }

    public static String getryName() {
        return getUser((String) SPUtils.get(Constants.current_id, "")).ryname;
    }

}
